define(["../common"], function() {
	var $list = $(".addr-list");
	var $loadTip = $(".mr a");
	// 加载列表数据
	$.getJSON(g_userDomain + "/address/list/json", function(data) {
		if (data.status !== 0) {
			$loadTip.html(data.message);
			return;
		}
		var def = data.result.address;
		if (!def) {
			$loadTip.html("查无记录");
			return;
		}
		$loadTip.hide();
		$list.show();
		
		$list.parseHtml({data: data.result.addresses});
		
		// 默认地址
		if ($("#address_" + def.addressId).length > 0) {
			$("#address_" + def.addressId).find(".label").removeClass("hidden");
		}
		
	});
	
	// 编辑
	$(document).on('click', "[id^=address_]", function() {
		var id = ($(this).attr("id").split("_"))[1];
		location.href = g_userDomain + "/address/addOrEdit?addressId=" + id;
	});
	
	// 删除
	$(document).on('click', ".close", function () {
		var $this = $(this);
		if (!$this.lock()) {
			return;
		}
		$this.loadMsg("删除...")
		var id = ($this.parent().attr("id").split("_"))[1];
		$.post(g_userDomain + "/address/delDo/json", {addressId: id}, function(data) {
			// 删除失败，则刷新页面
			if (data.status !== 0) {
				$this.failMsg(data.message);
				setTimeout(function() {
					window.reload();
				}, 2000);
				return;
			}
			$this.infoMsg("删除成功");
			// 返回的是默认收货地址, 因为之前有可能删除的就是默认地址,它会随机选择其它一个作为默认地址
			var defAddress = data.result;
			$("#address_" + defAddress.addressId).find(".label").removeClass("hidden");
		})
		return false;
	});
	
	// 去新增
	$("#btn_add").click(function() {
		location.href = g_userDomain + "/address/addOrEdit";
	});
});